package cn.edu.ecust.seckill.controller;

import cn.edu.ecust.seckill.config.Task;
import cn.edu.ecust.seckill.config.TaskQueue;
import cn.edu.ecust.seckill.result.Result;
import cn.edu.ecust.seckill.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

@RestController
public class SeckillControllerNew {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private List<TaskQueue> taskQueueList;

    private ConcurrentHashMap<Long, Object> userMap = new ConcurrentHashMap();

    /**
     * 秒杀抢单
     * 必须登录 必须没买过 必须有库存
     */
    @PostMapping("/seckill/new/{productId}/order")
    public Result<Void> seckill(@PathVariable Long productId, HttpServletRequest request) throws InterruptedException {

        // 认证
        String token = request.getHeader("token");
        Claims claims = JwtUtil.parserToken(token);
        if(claims == null){
            return Result.fail(401, "请先登录");
        }
        Long userId = claims.get("id", Long.class);

        // 本地过滤重复参与
        if(userMap.containsKey(userId)) {
            return Result.fail(401, "您已参与过该次秒杀，请耐心等待结果");
        }

        // 加入队列
        Task task = new Task(userId, productId, new CompletableFuture<>());
        taskQueueList.get(userId.intValue() % taskQueueList.size()).put(task);

        // 等待返回
        return task.getCompletableFuture().join();
    }

}
